<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class WdminAjax extends Controller {

    /**
     * 查看订单<发货>
     */
    const ORDER_EXP = 0;

    /**
     * 查看订单
     */
    const ORDER_VIE = 1;

    public function __construct($ControllerName, $Action, $QueryString) {
        parent::__construct($ControllerName, $Action, $QueryString);
        $this->loadModel('Db');
    }

    /**
     * 上传群发封面图片
     * groupSendImageUpload
     */
    public function BannerImageUpload() {
        if (!empty($_FILES)) {
            $dirname = dirname(__FILE__) . "/../static/banner/";
            $tempFile = $_FILES['jUploaderFile']['tmp_name'];
            $targetPath = $dirname;
            $namex = explode(".", $_FILES['jUploaderFile']['name']);
            // @rename
            $targetFileName = md5($_COOKIE['_uid'] . time()) . '.' . $namex[1];
            $targetFile = str_replace('//', '/', $targetPath) . $targetFileName;

            $state = move_uploaded_file($tempFile, $targetFile) ? 1 : 0;
            chmod($targetFile, 0777);

            if ($state == 1) {
                if (@$dims = getimagesize($targetFile)) {
                    $imginfo = array(
                        "width" => $dims[0],
                        "height" => $dims[1]
                    );
                } else
                    $imginfo = null;
            }
        } else {
            $state = 0;
        }
        $arr = array(
            "s" => $state,
            "pic" => $dirname . $targetFileName,
            "imgn" => $targetFileName,
            "size" => $imginfo
        );

        $json = json_encode($arr);
        print_r($json);
    }

    /**
     * 上传群发封面图片
     * groupSendImageUpload
     */
    public function groupSendImageUpload($Query) {
        global $config;
        !isset($Query->name) && $Query->name = '';
        if (!empty($GLOBALS["HTTP_RAW_POST_DATA"])) {
            $targetPath = dirname(__FILE__) . "/../static/groupsend_upload/";
            $targetFileName = sha1(time()) . '-' . $Query->name;
            $targetFile = str_replace('//', '/', $targetPath) . $targetFileName;
            $state = file_put_contents($targetFile, $GLOBALS["HTTP_RAW_POST_DATA"]) > 0 ? 1 : 0;
        } else {
            $state = 0;
        }
        $this->echoJson(array(
            "status" => $state,
            "imagepath" => urlencode("http://" . $_SERVER['HTTP_HOST'] . $config->shoproot . 'static/groupsend_upload/' . $targetFileName),
            "imagename" => $targetFileName
        ));
    }

    /**
     * 创建群发页面
     * @param type $Query
     */
    public function alterGmessPage($Query) {
        global $config;

        // 是否为更新
        $isUpdate = isset($Query->isUpdate) ? $Query->isUpdate == 1 : false;

        if ($isUpdate) {
            /**
             * 修改保存gmess
             */
            $SQL = sprintf("UPDATE `gmess_page` SET `title` = '%s',`content` = '%s',`desc` = '%s',`catimg` = '%s' WHERE `id` = %s AND `appid` = '%s';", $_POST['title'], $_POST['content'], $_POST['desc'], urldecode($_POST['catimg']), (int) $_POST['msgid'], APPID);
            $rst = $this->Db->query($SQL);
            $this->echoJson(array(
                'status' => $rst ? 1 : 0
            ));
        } else {
            /**
             * 创建gmess
             */
            $SQL = sprintf("INSERT INTO `gmess_page` (`title`,`content`,`desc`,`catimg`,`createtime`,`appid`)"
                    . " VALUES ('%s','%s','%s','%s',NOW(),'%s');", $this->post('title'), $_POST['content'], $_POST['desc'], urldecode($_POST['catimg']), APPID);
            $rst = $this->Db->query($SQL);
            $ret = array();
            if ($rst) {
                $ret['status'] = 1;
                $ret['url'] = "http://" . $this->server('HTTP_HOST') . "$config->shoproot?/Gmess/view/id=" . $rst;
                $ret['msgid'] = $rst;
            } else {
                $ret['status'] = 0;
            }
            $this->echoJson($ret);
        }
    }

    // 获取订阅者列表
    // todo
    public function ajaxGetSubScribelist() {
        $this->loadModel('WechatSdk');
        $access_token = WechatSdk::getServiceAccessToken();
        $list = WechatSdk::getWechatSubscriberList($access_token);
        $list['accesstoken'] = $access_token;
        $this->echoJson($list);
    }

    // 上传群发统计数据
    public function UploadGroupSendStatData() {
        $SQL = sprintf("INSERT INTO `gmess_send_stat` (msg_id,send_date,send_count,receive_count,appid,msg_type) "
                . " VALUES (%s,NOW(),%s,%s,'%s','images');", $_POST['msgid'], $_POST['total'], $_POST['success'], APPID);
        $rst = $this->Db->query($SQL);
        echo $rst ? 1 : 0;
    }

    /**
     * 获取已发列表
     * @param type $Query
     */
    public function ajaxGetGroupSent($Query) {
        global $config;
        $list = $this->Db->query(sprintf("SELECT * FROM `gmess_page` RIGHT JOIN `gmess_send_stat` on gmess_page.id = gmess_send_stat.msg_id WHERE `gmess_page`.`appid` = '%s' ORDER BY `send_date` DESC;", APPID));
        foreach ($list as &$l) {
            $l['reach_rate'] = $l['receive_count'] == 0 ? 0 : sprintf('%.2f', ($l['receive_count'] / $l['send_count']) * 100);
            $l['send_date'] = date("n月d日", strtotime($l['send_date']));
            $l['href'] = "http://" . $this->server('HTTP_HOST') . "$config->shoproot?/Gmess/view/id=" . $l['msg_id'];
        }
        $this->Smarty->assign('list', $list);
        $this->show();
    }

    /**
     * 获取图文列表
     * @param type $Query
     */
    public function ajaxGetGmessList($Query) {
        global $config;
        $list = $this->Db->query(sprintf("SELECT * FROM `gmess_page` WHERE `gmess_page`.`appid` = '%s' ORDER BY `createtime` DESC;", APPID));
        foreach ($list as &$l) {
            $l['href'] = "http://" . $this->server('HTTP_HOST') . "$config->shoproot?/Gmess/view/id=" . $l['id'];
        }
        $this->Smarty->assign('list', $list);
        $this->show();
    }

    /**
     * 获取图文列表2
     * @param type $Query
     */
    public function ajaxGetGmessList2($Query) {
        global $config;
        $list = $this->Db->query(sprintf("SELECT * FROM `gmess_page` WHERE `gmess_page`.`appid` = '%s' ORDER BY `createtime` DESC;", APPID));
        foreach ($list as &$l) {
            $l['href'] = "http://" . $this->server('HTTP_HOST') . "$config->shoproot?/Gmess/view/id=" . $l['id'];
        }
        $this->Smarty->assign('list', $list);
        $this->show();
    }

    /**
     * 获取商品详细信息
     * @param type $Query
     */
    public function ajaxGetProductInfo($Query) {
        $id = intval($Query->id);
        $res = $this->Db->query("SELECT * FROM `products_info` pi LEFT JOIN product_onsale po ON po.product_id = pi.product_id WHERE pi.`product_id` = $id;");
        $res = $res[0];
        $res['images'] = $this->Db->query("SELECT * FROM `product_images` WHERE `product_id` = " . $res['product_id']);
        $this->echoJson($res);
    }

    /**
     * 获取订单详情
     * @param type $Query
     */
    public function loadOrderDetail($Query) {
        $id = intval($Query->id);
        $this->loadModel('mOrder');
        if (!isset($Query->mod)) {
            $Query->mod = self::ORDER_EXP;
        } else {
            $Query->mod = intval($Query->mod);
        }
        // get data
        $data = $this->mOrder->wdminGetOrderDetail($id);
        #var_dump($data);
        // assign
        $this->Smarty->assign('expressCompany', include dirname(__FILE__) . '/../config/express_code.php');
        $this->Smarty->assign('data', $data);
        $this->Smarty->assign('mod', $Query->mod);
        $this->show();
    }

    /**
     * 管理后台加载报表页
     * @param type $Query
     */
    public function ajaxLoadStatHome($Query) {
        $QueryDate = date("Y-m-d");
        $QueryMonth = date("Y-m");
        // 日销售
        $DaySaleData = $this->Db->query("SELECT * FROM `vstatdaysalesumraw` WHERE `day` = '$QueryDate';");
        // 月销售
        $MonthSaleData = $this->Db->query("SELECT * FROM `vstatmonthsalesumraw` WHERE `month` = '$QueryMonth';");
        // 微信总关注
        $wechatSub = $this->Db->query("SELECT SUM(dv) AS sc FROM `wechat_subscribe_record`;");
        // 微信今天关注
        $wechatSubDay = $this->Db->query("SELECT SUM(dv) AS sc FROM `wechat_subscribe_record` WHERE DATE_FORMAT(`date`,'%Y-%m-%d') = '$QueryDate';");
        // 微信关注记录
        $WechatSubscribeStat = $this->Db->query("SELECT * FROM `vwechatsubscribestat` WHERE DATE_FORMAT(`date`,'%Y-%m') = '$QueryMonth';");
        $data_wechatsc = array();
        foreach ($WechatSubscribeStat as $_record) {
            $data_wechatsc['day'][] = intval(date("d", strtotime($_record['date'])));
            $data_wechatsc['count'][] = $_record['count'];
        }

        $wecahtCount = isset($data_wechatsc['count']) ? implode(',', $data_wechatsc['count']) : '';
        $wecahtDay = isset($data_wechatsc['day']) ? implode(',', $data_wechatsc['day']) : '';

        $this->Smarty->assign('wecahtCount', $wecahtCount);
        $this->Smarty->assign('wecahtDay', $wecahtDay);
        $this->Smarty->assign('daysale', $DaySaleData[0]);
        $this->Smarty->assign('monthsale', $MonthSaleData[0]);
        $this->Smarty->assign('wechatSubDay', $wechatSubDay[0]['sc']);
        $this->Smarty->assign('wechatSubTotal', $wechatSub[0]['sc']);
        $this->show();
    }

    /**
     * 更新商品信息
     */
    public function updateProduct() {
        $this->loadModel('Product');
        $this->Product->modifyProduct($_POST);
        echo 1;
    }

    /**
     * 加载系统设置
     */
    public function ajaxLoadSettings() {
        $set = $this->getShopSettings();

        $this->echoJson($set);
    }

    public function getAutoReplys() {
        $this->echoJson($this->Db->query("SELECT * FROM `wechat_autoresponse` ORDER BY `id` DESC;"));
    }

    /**
     * 更新自动回复内容
     */
    public function setAutoReplys() {
        $SQL = "REPLACE INTO `wechat_autoresponse` (`id`,`key`,`message`) VALUES ";
        foreach ($_POST['data'] as $index => $data) {
            $sp = $index != 0 ? ',' : '';
            $SQL .= "$sp($data[id],'$data[key]','$data[message]')";
        }
        $SQL = $SQL . ';';
        $ret = $this->Db->query($SQL);
        echo $ret;
    }

    /**
     * 更新自动回复内容
     */
    public function addAutoReplys() {
        $key = $_POST['key'];
        $SQL = "INSERT INTO `wechat_autoresponse` (`key`,`message`) VALUES ('$key','');";
        $ret = $this->Db->query($SQL);
        echo $ret;
    }

    /**
     * 删除自动回复关键字
     */
    public function deleteAutoReplys() {
        $id = intval($_POST['id']);
        $ret = $this->Db->query("DELETE FROM `wechat_autoresponse` WHERE `id` = $id;");
        echo $ret == false ? 0 : 1;
    }

    /**
     * 更新系统设置
     */
    public function setSettings() {
        $SQL = sprintf("UPDATE `shop_settings` SET `shop_name` = '%s',`wechat_subscribe_welcome` = '%s',`company_profit_percent` = '%s';", $_POST['shop_name'], $_POST['wechat_subscribe_welcome'], $_POST['company_profit_percent']);
        echo $this->Db->query($SQL);
    }

    /**
     * 获取微代理未结算数据
     * @return type
     */
    public function getCompanyCslist() {
        $this->loadModel('mCompany');
        $list = $this->mCompany->getCompanyCashs();
        #var_dump($list);
        $this->Smarty->assign('olist', count($list));
        $this->Smarty->assign('list', $list);
        $this->show();
    }

    public function companyCash($Query) {
        $this->loadModel('mCompany');
        $list = $this->mCompany->getCompanyCashs($Query->id);
        $this->Smarty->assign('list', $list[0]);
        $this->show();
    }

    public function cashCompanyReq() {
        $uid = $_POST['uid'];
        $this->Db->query(sprintf("UPDATE `companys` SET `bank_name` = '%s',`bank_account` = '%s',`bank_personname` = '%s' WHERE `uid` = '$uid';", $_POST['bank_name'], $_POST['bank_account'], $_POST['bank_personname']));
        echo $this->Db->query("UPDATE `company_income_record` SET `is_reqed` = 1 WHERE `is_seted` = 0 AND `is_reqed` = 0 AND `com_id` = '$uid';");
    }

    public function cashCompany() {
        $this->loadModel('mCompany');
        echo $this->mCompany->cashCompany($_POST['uid']);
    }

    /**
     * 删除商品
     */
    public function deleteProduct() {
        $id = intval($this->pPost('id'));
        $this->loadModel('Product');
        echo $this->Product->deleteProduct($id);
    }

    /**
     * 会员列表
     */
    public function ajaxUserList() {
        $list = $this->Db->query("SELECT *,cl.client_id as cid FROM `clients` cl
LEFT JOIN `client_infos` ci on ci.client_id = cl.client_id
LEFT JOIN `client_info_exts` cx on cx.client_id = ci.client_id ORDER BY cl.client_id DESC;");

        foreach ($list AS &$l) {
            $l['client_sex'] = $this->sexConv($l['client_sex']);
        }

        $this->Smarty->assign('list', $list);
        $this->show();
    }

    /**
     * 性别eng转换
     * @param type $sex
     * @return string
     */
    private function sexConv($sex) {
        $s = array('f' => '女', 'm' => '男');
        return $s[$sex];
    }

    /**
     * 获取横幅数据
     */
    public function getBannerData() {
        $dat = $this->Db->query("SELECT * FROM `ws_banner`;");
        $this->echoJson($dat);
    }

    public function SaveBannerData() {
        echo $this->Db->query(sprintf("UPDATE `ws_banner` SET `banner_image` = '%s',`banner_href` = '%s' WHERE `relid` = %s;", $this->post('img'), $this->post('href'), $this->post('relid')));
    }

    /**
     * 获取素材
     * @param type $Query
     */
    public function ajaxGmess($Query) {
        global $config;
        $id = intval($Query->id);
        $page = $this->Db->query("SELECT * FROM `gmess_page` WHERE `id` = $id;");
        $page = $page[0];
        $page['href'] = "http://" . $this->server('HTTP_HOST') . "$config->shoproot?/Gmess/view/id=" . $page['id'];
        $this->Smarty->assign('gm', $page);
        $this->show();
    }

    /**
     * 修改自动回复
     */
    public function updateAutoReply() {
        echo $this->Db->query(sprintf("UPDATE `wechat_autoresponse` SET `rel` = %s WHERE `id` = %s;", $this->post('rel'), $this->post('id')));
        # echo sprintf("UPDATE `wechat_autoresponse` SET `rel` = %s WHERE `id` = %s;", $this->post('rel'), $this->post('id'));
    }

}
